import { view } from './view-state.js';
import { AXIS_LEFT, AXIS_BOTTOM, freqToX, dbToY } from './canvas-utils.js';

export function drawSpectrum(canvas, data) {
    if (!data) return;
    const ctx = canvas.getContext('2d');
    const w = canvas.width;
    const h = canvas.height;
    ctx.clearRect(0, 0, w, h);

    // Y轴刻度
    ctx.fillStyle = "#aaa";
    ctx.font = "12px Arial";
    ctx.textAlign = "right";
    for (let db = Math.floor(view.maxDb / 10) * 10; db >= Math.ceil(view.minDb / 10) * 10; db -= 10) {
        if (db > view.maxDb || db < view.minDb) continue;
        const y = dbToY(db, canvas, view);
        ctx.fillText(`${db}`, AXIS_LEFT - 8, y + 4);
        ctx.strokeStyle = "rgba(255,255,255,0.1)";
        ctx.beginPath();
        ctx.moveTo(AXIS_LEFT, y);
        ctx.lineTo(w, y);
        ctx.stroke();
    }

    // 频谱曲线
    ctx.strokeStyle = "#33ff55";
    ctx.lineWidth = 1.5;
    ctx.beginPath();
    data.forEach((db, i) => {
        const freq = view.centerFreq - view.bandwidth / 2 + (i / (data.length - 1)) * view.bandwidth;
        const x = freqToX(freq, canvas, view);
        const y = dbToY(db, canvas, view);
        if (i === 0) ctx.moveTo(x, y);
        else ctx.lineTo(x, y);
    });
    ctx.stroke();

    // X轴刻度（底部）
    ctx.textAlign = "center";
    ctx.textBaseline = "top";
    const step = niceStep(view.bandwidth);
    for (let f = Math.floor((view.centerFreq - view.bandwidth/2) / step) * step;
         f <= view.centerFreq + view.bandwidth/2; f += step) {
        const x = freqToX(f, canvas, view);
        ctx.fillText(f.toFixed(2), x, h - AXIS_BOTTOM + 10);
        ctx.strokeStyle = "rgba(255,255,255,0.15)";
        ctx.beginPath();
        ctx.moveTo(x, 0);
        ctx.lineTo(x, h - AXIS_BOTTOM);
        ctx.stroke();
    }

    // 中心频率提示
    ctx.fillStyle = "#fff";
    ctx.textAlign = "left";
    ctx.fillText(`中心: ${view.centerFreq.toFixed(3)} MHz   带宽: ${view.bandwidth.toFixed(3)} MHz`, 10, 15);
}

// 产生美观的刻度间隔
function niceStep(range) {
    const rough = range / 10;
    const exp = Math.pow(10, Math.floor(Math.log10(rough)));
    const mantissa = rough / exp;
    if (mantissa > 5) return 10 * exp;
    if (mantissa > 2) return 5 * exp;
    return 2 * exp;
}